from db import read_data, save_data
from interface import login_user_dict, get_pay_pwd


def verify_pay_pwd():  # 验证交易密码
    '''

    :return: 验证是否与交易密码一致
    '''
    pay_pwd = get_pay_pwd()
    if pay_pwd[:-4] != login_user_dict['pay_pwd'][:-4]:
        return False, "交易密码输入有误！"
    else:
        return True, '输入正确'


def verify_balance(tag=None):  # 验证金额
    '''

    :param tag: 如果tag是充值，那么就不验证是否小于余额
    :return: 输入的金额
    '''
    login_user = login_user_dict['username']
    # 读取当前用户余额
    flag_read, reading_data = read_data(tag='info', path=f"{login_user}_info.json")
    if not flag_read:
        return flag_read, reading_data
    balance_input = input("请输入交易金额:").strip()
    if not balance_input.isdigit():
        return False, "请输入数字！"
    balance = int(balance_input)
    user_balance = reading_data[login_user]['balance']
    if 0 > balance:
        return False, "金额输入有误!"
    if tag != 'recharge' and balance > user_balance:
        return False, "余额不足"
    return True, balance


def save_balance(tag, balance, username):
    '''

    :param tag: 加钱还是减钱
    :param balance: 金额是多少
    :param username: 对象是谁
    :return:
    '''
    flag_read, reading_data = read_data(tag='info', path=f"{username}_info.json")
    if not flag_read:
        return flag_read, reading_data
    # 收钱方和减钱方都会被读取出来数据
    old_balance = reading_data[username]['balance']
    new_balance = 0  #
    if tag == 'add':
        new_balance = old_balance - balance
    elif tag == 'minus':
        new_balance = old_balance + balance
    else:  # 其他tag还没想到 如果没有 新余额为0
        pass
    reading_data[username]['balance'] = new_balance
    flag_save, msg = save_data(tag='info', path=f"{username}_info.json", data=reading_data)
    if not flag_save:
        return flag_save, msg
    return True, '转账成功'
